package com.zhouchao.register.strategy;

import com.zhouchao.register.zookeeper.ZookeeperRegisterManager;
import com.zhouchao.rpc.common.Server;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Author: zhouchao
 * @Date: 2021/08/10 21:25
 * @Description:
 */
@Slf4j
public class RoundRule implements IRule {
    private static AtomicInteger nextServerCyclicCounter = new AtomicInteger(0);

    private static final ZookeeperRegisterManager REGISTER_MANAGER = new ZookeeperRegisterManager();

    @Override
    public Server choose() {
        List<Server> serverList = REGISTER_MANAGER.discover();
        if (serverList.isEmpty()){
            throw new RuntimeException("没有可用的服务");
        }

        int current = nextServerCyclicCounter.get();
        int serverCount = serverList.size();
        int next = (current + 1) % serverCount;
        nextServerCyclicCounter.compareAndSet(current,next);
        return serverList.get(next);
    }
}
